<style scoped>
.el-dropdown {
  margin-top: 5px;
}
</style>
<template>
  <div class="app-container">
    <el-row :gutter="20">

      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select v-model="queryParams.deptId" @keyup.enter="handleQuery" :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择部门"
              check-strictly clearable filterable />
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="线路" prop="routeId">
            <el-select v-model="queryParams.routeId" filterable placeholder="" @keyup.enter="handleQuery">
              <el-option v-for="item in routeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['dispatch:schedulingPlan:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
              v-hasPermi="['dispatch:schedulingPlan:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['dispatch:schedulingPlan:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['dispatch:schedulingPlan:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="schedulingPlanList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="ID" align="center" prop="id" v-if="true" />
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="线路名称" align="center" prop="routeName" />
          <el-table-column label="生成方式" align="center" prop="generateType">
            <template #default="scope">
              <dict-tag :options="dispatch_generate_type" :value="scope.row.generateType" />
            </template>
          </el-table-column>
          <el-table-column label="总趟次" align="center" prop="totalTimes" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="自动生成" align="center" prop="autoScheduling">
            <template #default="scope">
              <dict-tag :options="autoScheduling" :value="scope.row.autoScheduling" />
            </template>
          </el-table-column>
          <el-table-column label="启用范围" align="center" prop="usedScope">
            <template #default="scope">
              <dict-tag :options="dispatch_week" :value="scope.row.usedScope ? scope.row.usedScope.split(',') : []"
                :showValue="false" />
            </template>
          </el-table-column>
          <el-table-column label="生效日期" align="center" prop="usedStartTime" width="120">
            <template #default="scope">
              <span>{{ parseTime(scope.row.usedStartTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束日期" align="center" prop="usedEndTime" width="120">
            <template #default="scope">
              <span>{{ parseTime(scope.row.usedEndTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="sys_data_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" size="small" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['dispatch:schedulingPlan:edit']">修改</el-button>
              <el-dropdown trigger="click" type="primary">
                <span class="el-dropdown-link">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <div  v-hasPermi="['dispatch:schedulingPlanTimetable:list']" @click="openPlanDialog(scope.row)">
                      <el-dropdown-item>
                        <el-button link type="primary" size="small" icon="Edit">管理发车时刻</el-button>
                      </el-dropdown-item>
                    </div>
                    <div @click="openPlanGroup(scope.row)" v-hasPermi="['dispatch:schedulingPlanGrouping:list']"
                      v-if="scope.row.generateType == 3">
                      <el-dropdown-item>
                        <el-button link type="primary" size="small" icon="Edit">部位分组</el-button>
                      </el-dropdown-item>
                    </div>
                    <div v-hasPermi="['dispatch:schedulingPlanTimetable:list']" @click="onlyShowFunc(scope.row)">
                      <el-dropdown-item>
                        <el-button link type="primary" size="small" icon="List">发车时刻表</el-button>
                      </el-dropdown-item>
                    </div>
                    <div v-hasPermi="['dispatch:schedulingPlan:remove']" @click="handleDelete(scope.row)">
                      <el-dropdown-item>
                        <el-button link type="primary" size="small" icon="Delete">删除</el-button>
                      </el-dropdown-item>
                    </div>

                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>


    <!-- 添加或修改排班计划对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="schedulingPlanRef" :model="form" :rules="rules" label-width="80px">
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select v-model="form.deptId" :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门"
                check-strictly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线路" prop="routeId">
              <el-select v-model="form.routeId" filterable placeholder="请选择线路">
                <el-option v-for="item in routeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自动排班" prop="autoScheduling">
              <el-select v-model="form.autoScheduling" placeholder="请选择">
                <el-option v-for="dict in autoScheduling" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成方式" prop="generateType">
              <el-select v-model="form.generateType" placeholder="请选择">
                <el-option v-for="dict in dispatch_generate_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status">
                <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.status == 0" :span="12">
            <el-form-item label="生效日期" prop="usedStartTime">
              <el-date-picker clearable v-model="form.usedStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择生效开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col v-if="form.status == 0"  :span="12">
            <el-form-item label="结束日期" prop="usedEndTime">
              <el-date-picker clearable v-model="form.usedEndTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择生效结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col v-if="form.status == 0"  :span="24">
            <el-form-item label="启用范围" prop="usedScope">
              <el-checkbox-group v-model="form.usedScope">
                <el-checkbox v-for="dict in dispatch_week" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 管理发车时刻 -->
    <el-dialog :title="schedulingPlanTitle" v-model="schedulingPlanOpen" width="80%" append-to-body>
      <placeList :plan-id="schedulingPlanId" :only-show="onlyShow" />
    </el-dialog>

    <!-- 管理部位分组 -->
    <el-dialog v-if="schedulingPlanGroupOpen" class="add_dialog" :title="schedulingPlanGroupTitle" v-model="schedulingPlanGroupOpen" width="800px"
      append-to-body>
      <schedulingPlanGrouping :plan-id="schedulingPlanId" />
    </el-dialog>
  </div>
</template>

<script setup name="SchedulingPlan">
import placeList from "./components/placeList.vue";
import schedulingPlanGrouping from "./components/schedulingPlanGrouping/index.vue";
import { listSchedulingPlan, getSchedulingPlan, delSchedulingPlan, addSchedulingPlan, updateSchedulingPlan } from "@/api/dispatch/schedulingPlan";
import { getRouteList } from "@/api/basic/route";
import { deptTreeSelect } from "@/api/system/user";
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const { dispatch_week, sys_data_status,dispatch_generate_type } = proxy.useDict('dispatch_week', 'sys_data_status','dispatch_generate_type');

const schedulingPlanList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);
const autoScheduling = ref([{ "label": "是", "value": 1, "elTagType": "default", "elTagClass": null }, { "label": "否", "value": 2, "elTagType": "default", "elTagClass": null }]);
const routes = ref([{ "label": "测试线路", "value": "1" }]);
const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    routeId: undefined,
    generateType: undefined,
    status: undefined,
    deptId: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    routeId: [
      { required: true, message: "线路ID不能为空", trigger: "blur" }
    ],
    generateType: [
      { required: true, message: "生成方式不能为空", trigger: "change" }
    ],
    usedStartTime: [
      { required: true, message: "自动生成不能为空", trigger: "change" }
    ],
    autoScheduling: [
      { required: true, message: "生效不能为空", trigger: "change" }
    ],
    usedEndTime: [
      { required: true, message: "结束不能为空", trigger: "change" }
    ],
    usedScope: [
      { required: true, message: "启用范围不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "部门ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
/** 查询排班计划列表 */
function getList() {
  loading.value = true;
  listSchedulingPlan(queryParams.value).then(response => {
    schedulingPlanList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    routeId: null,
    generateType:  parseInt(dispatch_generate_type.value[0].value),
    totalTimes: null,
    remark: null,
    autoScheduling: 2,
    usedScope: [],
    usedStartTime: null,
    usedEndTime: null,
    status: '0',
    deptId: deptOptions.value[0].id,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("schedulingPlanRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加排班计划";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getSchedulingPlan(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    form.value.usedScope = form.value.usedScope ? form.value.usedScope.split(",") :[];
    open.value = true;
    title.value = "修改排班计划";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulingPlanRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      form.value.usedScope = Array.isArray(form.value.usedScope) ? form.value.usedScope.join(",") : form.value.usedScope;
      if (form.value.id != null) {
        updateSchedulingPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addSchedulingPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除排班计划编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delSchedulingPlan(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dispatch/schedulingPlan/export', {
    ...queryParams.value
  }, `schedulingPlan_${new Date().getTime()}.xlsx`)
}
const schedulingPlanOpen = ref(false);
const schedulingPlanTitle = ref(null);
const schedulingPlanId = ref(null);
function openPlanDialog(row) {
  onlyShow.value = false
  schedulingPlanOpen.value = true
  schedulingPlanTitle.value = row.name
  schedulingPlanId.value = row.id
}
getDeptTree();
getList();
const routeList = ref([]);
function getRoute() {
  getRouteList().then(res => {
    routeList.value = res.rows
  })
}
getRoute()
const schedulingPlanGroupOpen = ref(false);
const schedulingPlanGroupTitle = ref(null);
//部位分组
function openPlanGroup(row) {
  schedulingPlanGroupOpen.value = true
  schedulingPlanGroupTitle.value = row.name + ',部位分组设置'
  schedulingPlanId.value = row.id
}
const onlyShow = ref(false);
//发车时刻表
function onlyShowFunc(row) {
  onlyShow.value = true
  schedulingPlanOpen.value = true
  schedulingPlanTitle.value = row.name
  schedulingPlanId.value = row.id
}
</script>